﻿/****************************************************************************
 * Application   : Freekick Desktop Manager
 * Author        : sfreekick
 * Email         : sfreekick@gmail.com
 * Copyright     : (C) 2008 sfreekick
 * **************************************************************************/

/****************************************************************************
 *  This file is part of FreeKickManager.
 *
 *  FreeKickManager is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  FreeKickManager is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with FreeKickManager. If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Text.RegularExpressions;

namespace FreeKickManager
{
    public partial class FrmBrowser : Form
    {
        private Partido part = null;

        private bool error = false;
        private string msgError = "";

        public FrmBrowser()
        {
            InitializeComponent();

            //Descargar reporte del partido
            descargarXml("http://www.freekick.org/public/getdata.php?getdata=matchreport&datatype=xml&id=" + part.id, "temp\\partido.xml");
            generarHtmlPartido();
            webBrowser1.Navigate(Application.StartupPath + "\\temp\\partido.html");

            //Descargar datos jugadores equipo contrario
            descargarXml("http://www.freekick.org/public/getdata.php?getdata=players&datatype=xml&clubid=" + part.idOponente, "temp\\otroequipo.xml");
            players lp = cargarXmlJugadores("temp\\otroequipo.xml");
            generarHtmlJugadores(lp);
        }

        public FrmBrowser(Partido part)
        {
            InitializeComponent();

            this.part = part;
            
            bworker.RunWorkerAsync();
        }

        private players cargarXmlJugadores(string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(players));

            FileStream fs = new FileStream(path, FileMode.Open);

            players p;

            p = (players)serializer.Deserialize(fs);

            fs.Close();

            return p;
        }

        private bool descargarXml(string url, string path)
        {
            bool res = true;

            try
            {
                StreamWriter sw = new StreamWriter(path, false, Encoding.Default, 8192);

                StringBuilder sb = new StringBuilder();

                byte[] buf = new byte[8192];

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                if (FrmPrincipal.opciones.obtenerOpcion("usarProxy").Equals("1"))
                {
                    request.Proxy = new System.Net.WebProxy(FrmPrincipal.opciones.obtenerOpcion("proxyUrl") + ":" + FrmPrincipal.opciones.obtenerOpcion("proxyPuerto"), true);
                    request.Proxy.Credentials = new NetworkCredential(FrmPrincipal.opciones.obtenerOpcion("proxyUsuario"), FrmPrincipal.opciones.obtenerOpcion("proxyPassword"), FrmPrincipal.opciones.obtenerOpcion("proxyDominio"));
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream resStream = response.GetResponseStream();

                string tempString = null;
                int count = 0;

                do
                {
                    count = resStream.Read(buf, 0, buf.Length);

                    if (count != 0)
                    {
                        tempString = Encoding.Default.GetString(buf, 0, count);

                        sb.Append(tempString);
                    }
                }
                while (count > 0);

                sw.Write(sb.ToString());

                sw.Close();
            }
            catch (Exception ex)
            {
                error = true;
                msgError = "Se ha producido un error en la descarga del fichero XML. Detalle del error:\n\n" + ex.Message;

                res = false;
            }

            return res;
        }

        private Jugador cargarJugador(player p)
        {
            Jugador j = new Jugador();

            j.id = Convert.ToInt32(p.id);
            j.tipo = p.type.Equals("outfielder") ? TipoJugador.Campo : TipoJugador.Portero;
            j.nombre = p.name.first;
            j.apellidos = p.name.last.Text[0];
            j.nick = p.name.nick;
            j.años = Convert.ToInt32(p.age.years);
            j.meses = Convert.ToInt32(p.age.months);
            j.dias = Convert.ToInt32(p.age.days);
            j.nacionalidad = p.nation;
            j.juvenil = p.age.youth;
            j.pierna = p.preferred_foot.Equals("right") ? Pierna.Diestro : Pierna.Zurdo;
            j.experiencia = p.experience;
            j.lealtad = p.loyalty;
            j.salario = Convert.ToInt32(p.salary.total);
            j.precioCompra = Convert.ToInt32(p.purchase_price);
            j.fechaEntrada = p.join_date;

            return j;
        }

        private void generarHtmlJugadores(players lp)
        {
            StreamWriter sw2 = new StreamWriter("temp\\otrosjugadores.html", false, Encoding.Default, 8192);
            string html2 = "<html><head></head><body>";

            foreach (player p in lp.player)
            {
                Jugador j = cargarJugador(p);

                html2 += "<a name=\"" + j.id + "\">";
                html2 += j.nombre + " " + j.apellidos + "<br/>";
                html2 += j.años + "<br/>";
                html2 += "<hr/>";
            }

            html2 += "</body></html>";

            sw2.Write(html2);
            sw2.Flush();
            sw2.Close();
        }

        private void generarHtmlPartido()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("temp\\partido.xml");

            XmlNodeList listaNodos = doc.GetElementsByTagName("text");

            if (listaNodos.Count > 0)
            {
                XmlNode nodoText = listaNodos[0];

                string html = nodoText.InnerText;
                html = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"layout.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"text.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"fixed.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"menu.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"match_report.css\" /></head>"   //<body style=\"font-family: verdana, arial, helvetica, sans-serif;font-size:10px;color:#FFFFFF;margin:10px;padding:0px;background-color:#060;\">"
                    + html
                    + "</body></html>";

                html = html.Replace("&lt;", "<");
                html = html.Replace("&gt;", ">");
                html = html.Replace("&amp;", "&");
                html = html.Replace("&quot;", "\"");

                html = html.Replace("color:#000000;", "color:#FFFFFF;");
                html = html.Replace("color=\"black\"", "color=\"white\"");

                html = html.Replace("<a href=\"?action=special&value=View_Player&value2=", "<a href=\"otrosjugadores.html#");

                //Se realiza la traducción del partido
                html = traducirPartido(html);

                StreamWriter sw = new StreamWriter("temp\\partido.html", false, Encoding.UTF8, 8192);
                sw.Write(html);
                sw.Flush();
                sw.Close();
            }
        }

        private string traducirPartido(string html)
        {
            Regex r = null;
            string htmlTraducido = html;
            string linea = "";

            try
            {
                StreamReader sr = new StreamReader("conf\\traduccion.txt", Encoding.UTF8);

                while ((linea = sr.ReadLine()) != null)
                {
                    string[] tokens = linea.Split(new string[] { "##" }, StringSplitOptions.RemoveEmptyEntries);

                    r = new Regex(tokens[0]);
                    htmlTraducido = r.Replace(htmlTraducido, tokens[1]);
                }

                sr.Close();
            }
            catch (Exception)
            {
                error = true;
                msgError = "Error fichero de traducción de partidos.";
            }

            return htmlTraducido;
        }

        private void bworker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (part != null)
            {
                //Descargar reporte del partido
                descargarXml("http://www.freekick.org/public/getdata.php?getdata=matchreport&datatype=xml&id=" + part.id, "temp\\partido.xml");
                generarHtmlPartido();
                webBrowser1.Navigate(Application.StartupPath + "\\temp\\partido.html");

                bworker.ReportProgress(1);

                //Descargar datos jugadores equipo contrario
                descargarXml("http://www.freekick.org/public/getdata.php?getdata=players&datatype=xml&clubid=" + part.idOponente, "temp\\otroequipo.xml");
                players lp = cargarXmlJugadores("temp\\otroequipo.xml");
                generarHtmlJugadores(lp);

                bworker.ReportProgress(1);
            }
            else
            {
                error = true;
                msgError = "No se puede recuperar el partido seleccionado.";
            }
        }

        private void bworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (error)
                MessageBox.Show(msgError, "Error");
            else
                lblMensaje.Text = "Datos descargados correctamente.";
        }

        private void bworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbProgreso.PerformStep();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.GoBack();
        }
    }
}
